package com.qiandao.xuexitong.controller;


import com.qiandao.xuexitong.common.Result;
import com.qiandao.xuexitong.constant.JwtClaimsConstant;
import com.qiandao.xuexitong.dto.LoginDTO;
import com.qiandao.xuexitong.entity.User;
import com.qiandao.xuexitong.properties.JwtProperties;
import com.qiandao.xuexitong.service.UserService;
import com.qiandao.xuexitong.util.JwtUtil;
import com.qiandao.xuexitong.vo.UserInfoVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表（学生、教师） 前端控制器
 * </p>
 *
 * @author YouJiao
 * @since 2025-04-11
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody @Valid LoginDTO dto) {
        // 验证用户名和密码
        User user = userService.verifyUser(dto.getUsername(), dto.getPassword());
        if (user == null) {
            return Result.error("用户名或密码错误");
        }
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        // 生成token
        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(),jwtProperties.getUserTtl(),claims);
        UserInfoVO uInfo = new UserInfoVO();
        BeanUtils.copyProperties(user, uInfo);
        uInfo.setToken(token);
        return Result.success(uInfo);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public Result<Object> getCurrentUser(@RequestHeader("Authorization") String token) {
        // 去掉Bearer前缀
        token = token.substring(7);

        // 获取claims
        Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(),token);

        return Result.success(claims);
    }
}